/**
 * Created by rekey on 1/2/14.
 */
var config = require('../config.js');
var qiniu = require('qiniu');
qiniu.conf.ACCESS_KEY = config.file.qiniu.ak;
qiniu.conf.SECRET_KEY = config.file.qiniu.sk;

function getToken(bucket) {
  var putPolicy = new qiniu.rs.PutPolicy(bucket);
  // putPolicy.callbackUrl = callbackUrl;
  // putPolicy.callbackBody = callbackBody;
  // putPolicy.returnUrl = returnUrl;
  // putPolicy.returnBody = returnBody;
  // putPolicy.asyncOps = asyncOps;
  // putPolicy.expires = expires;

  return putPolicy.token();
}

exports.stat = function (key, callback) {
  var client = new qiniu.rs.Client();
  client.stat(config.file.buck, key, function (err, ret) {
    if (!err) {
      // ok
      // ret has keys (hash, fsize, putTime, mimeType)
      callback(ret);
    } else {
      console.log(err);
      // http://docs.qiniu.com/api/file-handle.html#error-code
    }
  });
};

exports.upload = function (localFile, key, callback) {
  console.log(localFile, key);
  var upToken = getToken(config.file.qiniu.buck);
  var extra = new qiniu.io.PutExtra();
  // extra.params = params;
  // extra.mimeType = mimeType;
  // extra.crc32 = crc32;
  // extra.checkCrc = checkCrc;

  qiniu.io.putFile(upToken, key, localFile, extra, function (err, ret) {
    callback(null, ret);
  });
};